﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using fmtx.Framework.Cache;
using com.fmtx.Model;
using com.fmtx.IDal;
using fmtx.Framework.DALFactory;

public class ArticleCache
{
    private const int SIZE = 500;//片块大小

    /// <summary>
    /// 获取指定的文章缓存列表
    /// </summary>
    /// <param name="maxid"></param>
    /// <param name="size"></param>
    /// <param name="index"></param>
    /// <returns></returns>
    public static List<OutPut> Query(int maxid, int size,string keyword,int index=0)
    {
        DataCache cache = new DataCache(string.Format(CacheKey.ARTIVLE_LIST,index));
        IEnumerable<OutPut> list = cache.Get() as IEnumerable<OutPut>;
        if (list == null)
        {
            list = QueryBind(index,SIZE);
            if (list != null || list.Count() > 0)
            {
                cache.Set(list, 24 * 60 * 3);
            }
        }
        if (list != null && list.Count() != 0)
        {
            list = list.Where(m => m.IsUp==true);
        }
        if (maxid > 0 && list != null && list.Count() != 0)
        {
            list = list.Where(m => m.Id < maxid);
        }
        if (list != null&&!string.IsNullOrEmpty(keyword))
        {
            list = list.Where(w => (w.KeyWord != null && w.KeyWord.Contains(keyword)) || (w.Address != null && w.Address.Contains(keyword)) || (w.Title != null && w.Title.Contains(keyword)));
        }
        List<OutPut> resultlist = list.OrderByDescending(o => o.Id).Take(size).ToList();
        DataCache acount = new DataCache(CacheKey.ARTIVLE_COUNT);
        var allcount = acount.Get();
        if (allcount == null)
        {
            IArticle _article = DataAccess<IArticle>.GetObject();
            allcount = _article.GetCount();
            acount.SetByTime(allcount, 1 * 60);
        }
        int cusize = StaticCs.GetCuSize((int)allcount, SIZE);
        var cc = size - resultlist.Count;
        if (cc > 0 && cusize > index)
        {
            var olist = Query(maxid, cc, keyword, index + 1);
            if (olist != null && olist.Count != 0)
            {
                resultlist.AddRange(olist);
            }
        }
        return resultlist.ToList();
    }

    /// <summary>
    /// 插入一个文章
    /// </summary>
    /// <param name="model"></param>
    public static void Insert(Article model)
    {
        if (string.IsNullOrEmpty(model.FrontCover))
        {
            return;
        }
        DataCache cache = new DataCache(string.Format(CacheKey.ARTIVLE_LIST, 0));
        List<OutPut> list = cache.Get() as List<OutPut>;
        if (list != null)
        {
            list.Add(BindDetail(model));
        }
    }

    /// <summary>
    /// 插入一个文章
    /// </summary>
    /// <param name="model"></param>
    public static void Update(Article model,int index=0)
    {
         DataCache acount = new DataCache(CacheKey.ARTIVLE_COUNT);
        var allcount = acount.Get();
        if (allcount == null)
        {
            IArticle _article = DataAccess<IArticle>.GetObject();
            allcount = _article.GetCount();
            acount.SetByTime(allcount, 1 * 60);
        }
        int cusize = StaticCs.GetCuSize((int)allcount, SIZE);
        DataCache cache = new DataCache(string.Format(CacheKey.ARTIVLE_LIST, index));
        List<OutPut> list = cache.Get() as List<OutPut>;
        if (list != null)
        {
            var bean = list.Where(w => w.Id == model.Id).FirstOrDefault();
            if (bean == null && cusize>index)
            {
                Update(model, index++);
            }
            else {
                bean = BindDetail(model);
            }
        }
        else if (cusize > index)
        {
            Update(model, index++);
        }
    }

    /// <summary>
    /// 移除一个文章缓存
    /// </summary>
    /// <param name="id"></param>
    /// <param name="index"></param>
    public static void Remove(int id,int index=0)
    {
        DataCache acount = new DataCache(CacheKey.ARTIVLE_COUNT);
        var allcount = acount.Get();
        if (allcount == null)
        {
            IArticle _article = DataAccess<IArticle>.GetObject();
            allcount = _article.GetCount();
            acount.SetByTime(allcount, 1 * 60);
        }
        int cusize = StaticCs.GetCuSize((int)allcount, SIZE);
        DataCache cache = new DataCache(string.Format(CacheKey.ARTIVLE_LIST, index));
        List<OutPut> list = cache.Get() as List<OutPut>;
        if (list != null)
        {
            var model= list.Where(w=>w.Id==id).FirstOrDefault();
            if (model == null)
            {
                Remove(id, index++);
            }
            else if (cusize > index)
            {
                list.Remove(model);
            }
        }
        else if (cusize > index)
        {
            Remove(id, index++);
        }
    }

    /// <summary>
    /// 移除一个文章类型缓存
    /// </summary>
    /// <param name="id"></param>
    /// <param name="index"></param>
    public static void RemoveType(int id, int index = 0)
    {
        DataCache acount = new DataCache(CacheKey.ARTIVLE_COUNT);
        var allcount = acount.Get();
        if (allcount == null)
        {
            IArticle _article = DataAccess<IArticle>.GetObject();
            allcount = _article.GetCount();
            acount.SetByTime(allcount, 1 * 60);
        }
        int cusize = StaticCs.GetCuSize((int)allcount, SIZE);
        DataCache cache = new DataCache(string.Format(CacheKey.ARTIVLE_LIST, index));
        List<OutPut> list = cache.Get() as List<OutPut>;
        if (list != null)
        {
            var models = list.Where(w => w.TypeId == id);
            if (models != null)
            {
                foreach (var item in models)
                {
                    item.IsUp = false;
                }
            }
            else if (cusize > index)
            {
                RemoveType(id, index++);
            }
        }
        else if (cusize > index)
        {
            RemoveType(id, index++);
        }
    }

    /// <summary>
    /// 赞美文章
    /// </summary>
    /// <param name="model"></param>
    public static void DoSup(int id, int index = 0)
    {
        DataCache acount = new DataCache(CacheKey.ARTIVLE_COUNT);
        var allcount = acount.Get();
        if (allcount == null)
        {
            IArticle _article = DataAccess<IArticle>.GetObject();
            allcount = _article.GetCount();
            acount.SetByTime(allcount, 1 * 60);
        }
        int cusize = StaticCs.GetCuSize((int)allcount, SIZE);
        DataCache cache = new DataCache(string.Format(CacheKey.ARTIVLE_LIST, index));
        List<OutPut> list = cache.Get() as List<OutPut>;
        if (list != null)
        {
            var abean = list.Where(w => w.Id == id).FirstOrDefault();
            if (abean != null)
            {
                abean.SupCount++;
            }
            else if (cusize > index)
            {
                DoSup(id, index++);
            }
        }
        else if (cusize > index)
        {
            DoSup(id, index++);
        }
    }

    /// <summary>
    /// 插入评论
    /// </summary>
    /// <param name="model"></param>
    public static void InsertComment(Comment model,int index=0)
    {
        DataCache cache = new DataCache(string.Format(CacheKey.ARTIVLE_LIST, index));
        List<OutPut> list = cache.Get() as List<OutPut>;
        if (list != null)
        {
            var abean = list.Where(w => w.Id == model.TagId).FirstOrDefault();
            if (abean != null)
            {
                if (abean.Comments == null)
                {
                    abean.Comments = new List<Comments>();
                }
                abean.Comments.Add(BindComment(model));
                if (abean.Comments.Count > 3)
                {
                    abean.Comments.RemoveAt(0);
                }
            }
            else {
                InsertComment(model, index++);
            }
        }
    }

    /// <summary>
    /// 移除评论
    /// </summary>
    /// <param name="aid">文章id</param>
    /// <param name="id">评论id</param>
    public static void RemoveComment(int aid,int id, int index = 0)
    {
        DataCache cache = new DataCache(string.Format(CacheKey.ARTIVLE_LIST, index));
        List<OutPut> list = cache.Get() as List<OutPut>;
        if (list != null)
        {
            var abean = list.Where(w => w.Id == aid).FirstOrDefault();
            if (abean != null)
            {
                if (abean.Comments != null)
                {
                    abean.Comments.Where(w => w.Id == id).FirstOrDefault().IsUp = false;
                }
            }
            else
            {
                RemoveComment(aid,id, index++);
            }
        }
    }

    /// <summary>
    /// 单元数据绑定
    /// </summary>
    /// <param name="bean"></param>
    /// <returns></returns>
    public static OutPut BindDetail(Article bean)
    {
        IUserInfo user = DataAccess<IUserInfo>.GetObject();
        IComment comment = DataAccess<IComment>.GetObject();
        var u=user.Get(bean.Uid);
        OutPut model = new OutPut();
        model.Id = bean.Id;
        model.Title = bean.Title;
        model.Time = bean.InTime.ToLocalTime().ToString("yyyy-MM-dd HH:mm:ss");
        model.Pic = bean.FrontCover;
        model.Scale = bean.Scale;
        model.Uid = bean.Uid;
        model.Uname = u.Name;
        model.Header = u.Header;
        model.SupCount = bean.PraiseCount;
        model.CommentCount = bean.CommentCount;
        model.Address = bean.Address;
        model.AddressUrl = bean.AddressUrl;
        model.IsUp = true;
        model.IsSys = u.IsSystem;
        model.KeyWord = bean.KeyWord;
        model.TypeId = bean.TypeId;
        var clist=comment.Query(bean.Id, Target.ARTICLE,0,3);
        model.Comments =new List<Comments>();
        foreach (var item in clist)
	    {
            model.Comments.Add(BindComment(item));
	    }
        return model;
    }

    /// <summary>
    /// 绑定单个评论
    /// </summary>
    /// <param name="model"></param>
    /// <returns></returns>
    public static Comments BindComment(Comment model)
    {
        IUserInfo user = DataAccess<IUserInfo>.GetObject();
        Comments c = new Comments();
        c.Id = model.Id;
        c.Content = model.Content;
        c.Ip = model.Ip;
        c.Time = model.InTime.ToLocalTime().ToString("yyyy-MM-dd HH:mm:ss");
        c.Uid = model.Uid;
        var cu = user.Get(model.Uid);
        c.Uname = cu.Name;
        c.Header = cu.Header;
        return c;
    }

    /// <summary>
    /// 绑定文章数据
    /// </summary>
    /// <param name="index"></param>
    /// <returns></returns>
    public static List<OutPut> QueryBind(int index,int size)
    {
        IArticle article = DataAccess<IArticle>.GetObject();
        var alist = article.Query(index, size);
        List<OutPut> output = new List<OutPut>();
        foreach (var item in alist)
        {
            output.Add(BindDetail(item));
        }
        return output;
    }


    /// <summary>
    /// 获取今日关键字相关文章
    /// </summary>
    /// <param name="size"></param>
    /// <returns></returns>
    public static IList<Article> GetListByKeyword(int size,out string keyword)
    {
        DataCache cach = new DataCache(CacheKey.ARTICLE_KEYWORD_LIST);
        var list = cach.Get() as IList<Article>;
        DataCache cachTD = new DataCache(CacheKey.ARTICLE_KEYWORD_TODATE);
        keyword = cachTD.Get() as string;
        if (list == null)
        {
            IKeyWord _keyword = DataAccess<IKeyWord>.GetObject();
            List<string> keywords = _keyword.QueryHost(20, Target.ARTICLE).Select(s => s.Keyword).ToList();
            var randem = new Random((int)DateTime.Now.Ticks);
            var num = randem.Next(0, keywords.Count - 1);
            IArticle article = DataAccess<IArticle>.GetObject();
            keyword = keywords[num];
            list = article.QueryByKeyword(size, keyword);
            if (list != null&&list.Count>0)
            {
                cach.Set(list, 24 * 60);
                cachTD.Set(keyword,24*60);
            }
        }
        return list;
    }
}
